/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.commonmodel.core.session.distributed;

import com.inspur.edp.cef.api.session.ICefSession;
import com.inspur.edp.cef.api.session.ICefSessionItem;
import com.inspur.edp.commonmodel.core.session.distributed.dac.FuncSessionItemIncrement;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import lombok.Getter;
import lombok.Setter;

public class RootEditTokenImpl implements RootEditToken {

  @Getter
  private final ICefSession session;

  public RootEditTokenImpl(ICefSession session) {
    this.session = session;
//    this.id = LongGenerator.get();
//    this.layer = layer;
  }

  //public boolean outmost() {
//    return layer == 1;
//  }

  @Getter
  @Setter
  private Throwable exception;

  @Getter
  @Setter
  private String exceptionMsg;

  private boolean saved;

  @Override
  public void setSaved(boolean value) {
    saved = value;
  }

  @Override
  public boolean getSaved() {
    return saved;
  }

  private Map<String, FuncSessionItemIncrement> increments;

  public Collection<FuncSessionItemIncrement> getIncrements() {
    return increments == null ? null : increments.values();
  }

  @Override
  public FuncSessionItemIncrement getItemIncrement(String alias) {
    if (increments == null) {
      increments = new HashMap<>();
    }
    FuncSessionItemIncrement rez = increments.get(alias);
    if(rez == null) {
      increments.put(alias, (rez = new FuncSessionItemIncrement()));
      rez.setConfigId(alias);
      rez.setIndex(findIndex(alias));
    }
    return rez;
  }

  private final int findIndex(String alias) {
    int index = 0;
    for (String key : session.getSessionItems().keySet()) {
      if(key.equals(alias)) {
        return index;
      }
      index++;
    }
    throw new RuntimeException();
  }

  @Getter
  @Setter
  private List<ICefSessionItem> items;

  @Getter
  @Setter
  private Lock editLock;

  @Override
  public String getSessionId() {
    return session.getSessionId();
  }

  @Getter
  @Setter
  private Map<String, Object> callContext = new HashMap<>();

  public void putCallContextOnlyAbsent(String key, Object value) {
    if(callContext.putIfAbsent(key ,value) != null){
      throw new RuntimeException();
    }
  }
}

